package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.MyView.refresh.SwipyRefreshLayout;
import com.ramos.kuaixiao.MyView.refresh.SwipyRefreshLayoutDirection;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.CustomerAdapter;
import com.ramos.kuaixiao.db.AllCustomerDB;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.db.SaleCustomerDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.SaleCustomer;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;

public class ShopFragment extends Fragment implements OnClickListener, SwipyRefreshLayout.OnRefreshListener {
    private static String TAG = "ShopFragment";
    private View mView;
    private Context mContext;
    private final int TOP_REFRESH = 1;
    private final int BOTTOM_REFRESH = 2;
    private LinearLayout ll_unfinished_none;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    public final static int REFRESH_SUCCESS = 200;
    public final static int UPLOAD_ALL_SUCCESS = 300;
    public final static int UPLOAD_ALL_FAIL = 301;
    private CustomerAdapter mAdapter;
    private List<Customer> productList = new ArrayList<>();
    private List<Customer> temList = new ArrayList<>();
    private CommonLoading loading;
    private CommonLoading loading1;
    private int page = 1;
    private RecyclerView mRecyclerView;
    private SwipyRefreshLayout mRefreshLayout;
    private LinearLayoutManager mLinearLayoutManager;
    private boolean mIsRefresh = true;
    private boolean mIsLocalDB = false;
    SearchView searchview;
    GeocodeSearch geocoderSearch;
    CustomerDB db;
    private boolean mIsFilter = false;
    private List<Customer> mTmpList = new ArrayList<>();
    private List<Customer> mFilterList = new ArrayList<>();
    private List<Customer> mPageFilterList = new ArrayList<>();
    private int filterPage = 1;
    private String mFilterWord;
    LinearLayout title_reback;
    TextView title_text;
    LinearLayout sao_choose;
    private int i = 0;
    private int DELYED= 1000;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        container = (ViewGroup) mView.getParent();
        if (container != null) {
            container.removeView(mView);
        }
        return mView;
    }

    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        initView();
        Log.d("onUpgrade", "ShopFragment,App.isOldVersion:"+App.isOldVersion);
        if(App.isOldVersion){
            startActivity(new Intent(getContext(), LoadingActivity.class));
        } else {
            App.isOldVersion = false;
        }

        if (App.mUserChanged) {
            Log.d(TAG, "App.mUserChanged:true");
            //downloadData();
            loadData();
        } else {
            Log.d(TAG, "App.mUserChanged:false");
            //uploadCustomer();
            if(SharedPreference.getPreferInteger("isFirstLogin") == 0){
                loadData();
            } else {
                loadLocalDb(1);
                //initCustomer();
            }
        }
    }

    private void initCustomer() {
        Set<String> customers = new HashSet<>();
        List<SaleCustomer> list1 = new ArrayList<>();
        list1.addAll(new SaleCustomerDB().findAllCustomer());
        CommUtil.d(App.mContext,TAG, "tbl_SaleCustomer:" + list1.size());
        for (SaleCustomer sale : list1) {
            if (sale.getSaleId().equals(SharedPreference.getPreferString("id"))) {
                customers.add(sale.getCustomerId());
            }
        }

        List<Customer> tmplist = new ArrayList<>();
        List<Customer> list = new ArrayList<>();
        list.addAll(new AllCustomerDB().findAllCustomer());
        CommUtil.d(App.mContext,TAG, "tbl_Customer:" + list.size());
        CommUtil.d(App.mContext,TAG, "tbl_customers:" + customers.size());
        if (customers != null && customers.size() > 0) {
            for (Customer customer : list) {
                for (String s : customers) {
                    if (customer.getId().equals(s)) {
                        tmplist.add(customer);
                    }
                }
            }
            CommUtil.d(App.mContext,TAG, "tbl_Customer1:" + tmplist.size());
            CustomerDB customerDB1 = new CustomerDB();
            customerDB1.addAllCustomer(tmplist);
            App.mCustomerList.clear();
            App.mCustomerList.addAll(tmplist);
            App.isCustomerUpdating = false;

            ToastUtils.show("客户数据已加载完成，总共"+tmplist.size()+"条数据");

        } else {
            App.isCustomerUpdating = false;

            ToastUtils.show("未发现客户数据！");

        }
    }

    private void uploadCustomer() {
        if (!db.hasData() &&  SharedPreference.getPreferInteger("isFirstLogin") == 0 && Utils.isNetworkConnected(getActivity())) {
            Log.d(TAG, "loadData");
            loadData();
        } else {
            Log.d(TAG, "loadLocalDb");
            loadLocalDb(1);
        }
    }

    private void loadData(){
        loadLocalData();
    }

    private void loadLocalData() {
        App.mUserChanged = false;
        //loading.dismiss();
        loadLocalDb(1);
        SharedPreference.setPreferInteger("isFirstLogin", 1);
    }

    private void downloadData() {
        try {
            String url = NetUtils.CUSTOMER_ALL_WITH_USER;
            org.json.JSONObject object = new org.json.JSONObject();
            object.put("dealer", SharedPreference.getPreferString("dealer"));
            object.put("sale", SharedPreference.getPreferString("id"));
            Log.d(TAG, "CUSTOMER_ALL_LOCAL:path=" + object.toString());
            String encode = URLEncoder.encode(object.toString(), "UTF-8");
            String path = url + encode;
            Log.d(TAG, "CUSTOMER_ALL_LOCAL:path=" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(60000);
            client.get(path, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        App.mUserChanged = false;
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "CUSTOMER_ALL_LOCAL:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            SharedPreference.setPreferInteger("isFirstLogin", 1);
                            List<Customer> customerList = JSONArray.parseArray(jsonObejct.getJSONArray("data").toString(), Customer.class);
                            if (customerList != null && customerList.size() > 0) {
                                if (db.addAllCustomer(customerList) == 0) {
                                    loadLocalDb(1);
                                }
                                if (!mIsFilter) {
                                    mTmpList.clear();
                                    mTmpList.addAll(productList);
                                }
                                loading.dismiss();
                                ToastUtils.show("数据加载完成！");

                            } else {
                                loading.dismiss();
                                sendMessagea(UPLOAD_ALL_FAIL, "jsonObejct.getInteger != 200");
                            }
                        } else {
                            loading.dismiss();
                            sendMessagea(UPLOAD_ALL_FAIL, "jsonObejct.getInteger != 200");
                        }
                    } catch (Exception e) {
                        App.mUserChanged = false;
                        // TODO Auto-generated catch block
                        loading.dismiss();
                        //initData(1);
                        sendMessagea(UPLOAD_ALL_FAIL, e.toString());
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    ///initData(1);
                    loading.dismiss();
                    App.mUserChanged = false;
                    sendMessagea(UPLOAD_ALL_FAIL, error.toString());
                    error.printStackTrace();
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            App.mUserChanged = false;
            sendMessagea(UPLOAD_ALL_FAIL, e.toString());
            e.printStackTrace();
        }
    }

    private void loadLocalDb(int page) {
        App.mCustomerList.clear();
        App.mCustomerList.addAll(db.findAllCustomer());
        title_text.setText("商店(" + App.mCustomerList.size()+")");
        mIsLocalDB = true;
        if (page == 1) {
            productList.clear();
        }
        temList.clear();
        temList = db.findAllPageCustomer(page, 20);
        if (temList.size() > 0) {
            productList.addAll(temList);
            mRecyclerView.setVisibility(View.VISIBLE);
            ll_unfinished_none.setVisibility(View.GONE);
            mAdapter.notifyDataSetChanged();
            if (!mIsFilter) {
                mTmpList.clear();
                mTmpList.addAll(productList);
            }
            Log.d(TAG, "result " + temList.size() + " " + mTmpList.size());
            Product product = new Product(productList);
            product.executeOnExecutor(Executors.newCachedThreadPool());
        } else {
            if (productList.size() == 0) {
                Log.d(TAG, "productList.size() == 0");
                mRecyclerView.setVisibility(View.GONE);
                ll_unfinished_none.setVisibility(View.VISIBLE);
            } else {
                ToastUtils.show("已无更多数据");
            }
        }
        mRefreshLayout.setRefreshing(false);
    }

    private void initView() {
        db = new CustomerDB();
        mContext = getActivity();
        mView = LayoutInflater.from(mContext).inflate(R.layout.fragment_shop, null);

        title_reback = mView.findViewById(R.id.title_reback);
        title_text = mView.findViewById(R.id.title_text);
        sao_choose = mView.findViewById(R.id.sao_choose);
        title_reback.setVisibility(View.INVISIBLE);
        title_text.setText("商店");
        sao_choose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), CustomerActivity.class));
            }
        });

       /* searchview = (SearchView) mView.findViewById(R.id.shop_Searchview);
        int id = searchview.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchview.findViewById(id);
        textView.setTextSize(16);//字体、提示字体大小
        searchview.setQueryHint("搜索商店(至少输入两个字)");
        searchview.setIconified(false);
        searchview.setIconifiedByDefault(false);
        int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView magImage = (ImageView) searchview.findViewById(magId);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
        Class<?> c = searchview.getClass();
        try {
            Field f = c.getDeclaredField("mSearchPlate");//通过反射，获得类对象的一个属性对象
            f.setAccessible(true);//设置此私有属性是可访问的
            View v = (View) f.get(searchview);//获得属性的值
            v.setBackgroundColor(Color.TRANSPARENT);//设置此view的背景
        } catch (Exception e) {
            e.printStackTrace();
        }
*/
        ll_unfinished_none = (LinearLayout) mView.findViewById(R.id.ll_unfinished_none);
        ll_unfinished_none.setOnClickListener(this);
        mRefreshLayout = (SwipyRefreshLayout) mView.findViewById(R.id.allListView);
        mRefreshLayout.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.list_task);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new CustomerAdapter(mContext, productList);
        mAdapter.setUpdateCarListener(new UpdateListener());
        mRecyclerView.setAdapter(mAdapter);
       /* searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onQueryTextChange(String queryText) {
                mFilterWord = queryText;
                if (StringUtil.isEmpty(queryText)) {
                    if (mTmpList.size() > 0) {
                        mRecyclerView.setVisibility(View.VISIBLE);
                        ll_unfinished_none.setVisibility(View.GONE);
                        mAdapter.refresh(mTmpList);
                    }
                    mIsFilter = false;
                } else if (queryText.length() >= 2) {
                    mAdapter.getFilter().filter(queryText);
                }
                return true;
            }
        });*/
    }

    class UpdateListener implements CustomerAdapter.UpdateCarListener {
        @Override
        public void update(int num, List<Customer> tasklist) {
            if (tasklist == null || tasklist.size() == 0) {
                if (!StringUtil.isEmpty(mFilterWord)) {
                    mRecyclerView.setVisibility(View.GONE);
                    ll_unfinished_none.setVisibility(View.VISIBLE);
                }
            } else {
                mPageFilterList.clear();
                mFilterList.clear();
                mFilterList.addAll(tasklist);
                filterPage = 1;
                mRecyclerView.setVisibility(View.VISIBLE);
                ll_unfinished_none.setVisibility(View.GONE);
                mPageFilterList = getPageList(mFilterList);
                mAdapter.refresh(mPageFilterList);
                mIsFilter = true;
                Product product = new Product(mPageFilterList);
                product.executeOnExecutor(Executors.newCachedThreadPool());
            }
        }
    }

    @Override
    public void onRefresh(SwipyRefreshLayoutDirection direction) {
        if (mIsFilter) {
            if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
                if (filterPage < (mFilterList.size() - 1) / 20 + 1) {
                    ++filterPage;
                    List<Customer> products = getPageList(mFilterList);
                    if (products.size() > 0) {
                        mPageFilterList.addAll(products);
                        mAdapter.notifyDataSetChanged();
                        Product product = new Product(mPageFilterList);
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    }
                }
                mRefreshLayout.setRefreshing(false);
            } else {
                mRefreshLayout.setRefreshing(false);
            }
        } else {
            if (direction == SwipyRefreshLayoutDirection.TOP) {
                mIsRefresh = false;
                dataOption(TOP_REFRESH);
            } else {
                mIsRefresh = false;
                dataOption(BOTTOM_REFRESH);
            }
        }
    }

    private List<Customer> getPageList(List<Customer> mProducts) {
        List<Customer> products = new ArrayList<>();
        if (mProducts.size() <= 20) {
            if (filterPage == 1) {
                products.addAll(mProducts);
            }
        } else {
            int maxPage = (mProducts.size() - 1) / 20 + 1;
            if (filterPage < maxPage) {
                products.addAll(mProducts.subList((filterPage - 1) * 20, filterPage * 20));
            } else if (filterPage == maxPage) {
                products.addAll(mProducts.subList((filterPage - 1) * 20, mProducts.size()));
                ToastUtils.show("数据已加载完");
            }
        }
        return products;
    }

/*    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //可以在这里直接去处理fragment的hide和show
        searchview.clearFocus();
    }

    @Override
    public void onResume() {
        super.onResume();
        searchview.clearFocus();
    }*/

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_unfinished_none:
                loadLocalDb(1);
                break;
            default:
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    if (page == 1) {
                        App.CUSTOMER_RESULT = msg.obj.toString();
                        productList.clear();
                    }
                    temList.clear();
                    Log.d(TAG, "result " + msg.obj.toString());
                    JSONObject jsonObejct = JSONObject.parseObject(msg.obj.toString());
                    JSONObject data = jsonObejct.getJSONObject("data");
                    temList = JSONArray.parseArray(data.getJSONArray("rows").toString(), Customer.class);
                    if (temList.size() > 0) {
                        productList.addAll(temList);
                        mRecyclerView.setVisibility(View.VISIBLE);
                        ll_unfinished_none.setVisibility(View.GONE);
                        if (!mIsFilter) {
                            mTmpList.clear();
                            mTmpList.addAll(productList);
                        }
                        mAdapter.notifyDataSetChanged();
                        Product product = new Product(productList);
                        product.executeOnExecutor(Executors.newCachedThreadPool());
                    } else {
                        if (productList.size() == 0) {
                            mRecyclerView.setVisibility(View.GONE);
                            ll_unfinished_none.setVisibility(View.VISIBLE);
                        }
                    }
                    mRefreshLayout.setRefreshing(false);
                    //searchview.clearFocus();
                    break;
                case UPLOAD_FAIL:
                    mRefreshLayout.setRefreshing(false);
                    if (productList.size() == 0) {
                        mRecyclerView.setVisibility(View.GONE);
                        ll_unfinished_none.setVisibility(View.VISIBLE);
                    }
                    //searchview.clearFocus();
                    break;
                case REFRESH_SUCCESS:
                    List<Customer> productList = (List<Customer>) msg.obj;
                    mAdapter.refresh(productList);
                    if (!mIsFilter) {
                        mTmpList.clear();
                        mTmpList.addAll(productList);
                    }
                    //searchview.clearFocus();
                    break;

                case UPLOAD_ALL_SUCCESS:
                    break;
                case UPLOAD_ALL_FAIL:
                    mRecyclerView.setVisibility(View.GONE);
                    ll_unfinished_none.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };


    class Product extends AsyncTask<String, String, String> {
        private List<Customer> productList = new ArrayList<>();

        public Product(List<Customer> type) {
            productList = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < productList.size(); i++) {
                    final Customer customer = productList.get(i);
                    Log.d("onGeocodeSearched", "" + customer.getAddress() + " : " + customer.getCity());
                    if (!StringUtil.isEmpty(customer.getAddress()) && !StringUtil.isEmpty(customer.getCity())) {
                        geocoderSearch = new GeocodeSearch(mContext);
                        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                            @Override
                            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            }

                            @Override
                            public void onGeocodeSearched(GeocodeResult result, int rCode) {
                                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                                    if (result != null && result.getGeocodeAddressList() != null
                                            && result.getGeocodeAddressList().size() > 0) {
                                        GeocodeAddress address = result.getGeocodeAddressList().get(0);
                                        LatLonPoint latLonPoint = address.getLatLonPoint();
                                        //Log.d("onGeocodeSearched", latLonPoint.toString() + " " );
                                        if (latLonPoint != null && !StringUtil.isEmpty(SharedPreference.getPreferString("latitude"))
                                                && !StringUtil.isEmpty(SharedPreference.getPreferString("longitude"))) {
                                            double dis = Utils.getDistance(latLonPoint.getLatitude(), latLonPoint.getLongitude(), Double.valueOf(SharedPreference.getPreferString("latitude")),
                                                    Double.valueOf(SharedPreference.getPreferString("longitude")));
                                            customer.setDistance(String.valueOf(App.df1.format(dis)) + "");
                                            //mAdapter.refresh(productList);
                                            sendMessagea(REFRESH_SUCCESS, productList);
                                        }
                                    }
                                }
                            }
                        });
                        GeocodeQuery query = new GeocodeQuery(customer.getAddress(), customer.getCity());// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
                        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Log.d("onGeocodeSearched", "" + productList.size());
            //mAdapter.refresh(productList);
        }
    }

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    private void dataOption(int option) {
        switch (option) {
            case TOP_REFRESH:
                // 下拉刷新
                if (!mIsFilter) {
                    productList.clear();
                    page = 1;
                    if (mIsLocalDB) {
                        loadLocalDb(page);
                    } else {
                        //initData(page);
                    }
                }

                break;
            case BOTTOM_REFRESH:
                // 上拉加载更多
                if (!mIsFilter) {
                    page++;
                    if (mIsLocalDB) {
                        loadLocalDb(page);
                    } else {
                        //initData(page);
                    }
                }
                break;
        }
    }
}
